package com.team622.shop.user.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.team622.shop.common.exceptions.BusinessException;
import com.team622.shop.common.exceptions.enums.Resp;
import com.team622.shop.user.model.dto.AdminLoginDTO;
import com.team622.shop.user.model.entity.Admin;
import com.team622.shop.user.model.entity.Role;
import com.team622.shop.user.model.vo.AdminLoginVO;
import com.team622.shop.user.service.mapper.AdminMapper;
import com.team622.shop.user.service.service.AdminService;
import com.team622.shop.user.service.service.RoleService;
import com.team622.shop.user.service.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author team622
 * @since 2025-07-15
 */
@Slf4j
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {
    @Resource
    private RoleService roleService;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private HttpServletRequest request;


//    @Override
//    public void updatePassword(AdminUpdatePasswordDTO adminUpdatePasswordDTO) {
//        // 获取当前管理员ID
//        Long adminId = BaseContextHandler.get();
//        if (adminId == null) {
//            log.error("未获取到当前管理员ID");
//            throw new BusinessException(Resp.UNAUTHORIZED);
//        }
//
//        // 查询管理员信息
//        Admin admin = this.getById(adminId);
//        if (admin == null) {
//            log.error("管理员不存在, ID: {}", adminId);
//            throw new BusinessException(Resp.INVALID_USERNAME);
//        }
//
//        // 验证旧密码
//        if (!passwordEncoder.matches(adminUpdatePasswordDTO.getOldPassword(), admin.getPassword())) {
//            log.warn("管理员密码修改失败: 旧密码不匹配, ID: {}", adminId);
//            throw new BusinessException(Resp.INVALID_PASSWORD);
//        }
//
//        // 加密新密码
//        String encodedPassword = passwordEncoder.encode(adminUpdatePasswordDTO.getNewPassword());
//
//        // 更新密码
//        Admin updateAdmin = new Admin();
//        updateAdmin.setId(adminId);
//        updateAdmin.setPassword(encodedPassword);
//        if (!this.updateById(updateAdmin)) {
//            log.error("管理员密码更新失败, ID: {}", adminId);
//            throw new BusinessException(Resp.UPDATE_FAILED);
//        }
//
//        log.info("管理员密码修改成功, ID: {}", adminId);
//    }

    @Override
    public boolean checkToken() {
        String accessToken = request.getHeader("Authorization");
        String result = jwtUtil.validateAccessToken(accessToken);
        return "Valid".equals(result);
    }

    @Override
    public AdminLoginVO login(AdminLoginDTO adminLoginDTO) {
        // 参数校验
        if (adminLoginDTO == null || !StringUtils.hasText(adminLoginDTO.getUsername())
                || !StringUtils.hasText(adminLoginDTO.getPassword())) {
            log.warn("登录参数不完整: {}", adminLoginDTO);
            throw new BusinessException(Resp.INVALID_PARAM);
        }

        log.info("管理员登录尝试: {}", adminLoginDTO.getUsername());

        // 查询管理员信息
        LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Admin::getMobile, adminLoginDTO.getUsername());
        Admin admin = this.getOne(wrapper);

        if (admin == null) {
            log.warn("管理员账号不存在: {}", adminLoginDTO.getUsername());
            throw new BusinessException(Resp.INVALID_USERNAME);
        }

        // 密码验证
        if (!passwordEncoder.matches(adminLoginDTO.getPassword(), admin.getPassword())) {
            log.warn("管理员密码错误, 账号: {}", adminLoginDTO.getUsername());
            throw new BusinessException(Resp.INVALID_PASSWORD);
        }

        // 获取角色信息
        Role role = roleService.getRoleByAdminId(admin.getId());
        if (role == null) {
            log.error("管理员未分配角色, adminId: {}", admin.getId());
            throw new BusinessException(Resp.UNAUTHORIZED);
        }

        // 生成JWT token
        Claims claims = Jwts.claims();
        claims.put("adminId", admin.getId());
        claims.put("roleId", role.getId());
        claims.put("roleName", role.getRoleName());

        log.info("管理员登录成功: {}, 角色: {}", admin.getId(), role.getRoleName());

        return new AdminLoginVO(
                jwtUtil.generateAccessToken(claims),
                jwtUtil.generateRefreshToken(claims)
        );
    }


}
